package com.ljc;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author clj
 * @date 2022/12/8
 * @desc
 * You are given an array prices where prices[i] is the price of a given stock on the ith day.
 *
 * You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
 *
 * Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
 *
 * Example 1:
 * Input: prices = [7,1,5,3,6,4]
 * Output: 5
 * Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
 * Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
 *
 *  Example 2:
 * Input: prices = [7,6,4,3,1]
 * Output: 0
 * Explanation: In this case, no transactions are done and the max profit = 0.
 */
public class E121BestBuyAndSell {
    public static void main(String[] args) {
        List<Integer> prices = new ArrayList<Integer>(){{
            add(7);
            add(1);
            add(5);
            add(3);
            add(6);
            add(4);
        }};
        System.out.println(maxProfit(prices));

        int[] pricesArray = new int[]{7,1,5,3,6,4};
        System.out.println(maxProfit0(pricesArray));
        System.out.println(maxProfit2(pricesArray));
    }

    public static int maxProfit(List<Integer> prices) {
        int maxProfit = 0;

        for (int i = 0; i < prices.size()-1; i++) {
            for (int j = i+1 ; j < prices.size(); j++) {
                if (prices.get(j) > prices.get(i)) {
                    int profit = prices.get(j) - prices.get(i);
                    if (profit != 0 && profit > maxProfit) {
                        maxProfit = profit;
                    }
                }
            }
        }
        return maxProfit;
    }

    /**
     * 一次遍历
     * @param prices
     * @return
     */
    public static int maxProfit0(int[] prices) {
        //定义一个最小的买入价格
        int minPrice = Integer.MAX_VALUE;
        //定义一个最大的利润价格
        int maxProfit = 0;
        for (int price : prices) {
            if (price < minPrice) {
                minPrice = price;
            }else if (price - minPrice > maxProfit) {
                maxProfit = price - minPrice;
            }

        }
        return maxProfit;
    }

    /**
     * 暴力法：两次循环判断
     */
    public static int maxProfit2(int[] prices) {
        int maxProfit = 0;
        for (int i = 0; i < prices.length - 1; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                int profit = prices[j] - prices[i];
                if (profit > maxProfit) {
                    maxProfit = profit;
                }
            }
        }
        return maxProfit;
    }

}
